package day01;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Jetwang
 * @version 1.0
 * @since 2023/3/19 13:53
 */
public class BlockingQueue01<E> implements BlockingQueue<E>{
    private final E[] array;
    private int head;
    private int tail;
    private int size;

    @SuppressWarnings("all")
    public BlockingQueue01(int capacity) {
        array = (E[]) new Object[capacity];
    }

    private ReentrantLock lock = new ReentrantLock();
    private Condition headWaits = lock.newCondition();
    private Condition tailWaits = lock.newCondition();

    private boolean isEmpty() {
        return size == 0;
    }

    private boolean isFull() {
        return size == array.length;
    }

    @Override
    public void offer(E e) throws InterruptedException {
        lock.lockInterruptibly();
        try {
            // 循环等待
            while(isFull()) {
                tailWaits.await();
            }
            array[tail] = e;
            if (++tail == array.length) {
                tail = 0;
            }
            size++;
            // 唤醒出队
            headWaits.signal();
        } finally {
            lock.unlock();
        }
    }

    @Override
    public boolean offer(E e, long timeout) throws InterruptedException {
        lock.lockInterruptibly();
        try {
            long t = TimeUnit.MICROSECONDS.toNanos(timeout);
            // 循环等待
            while(isFull()) {
                // 放弃等待
                if (t <= 0) {
                    return false;
                }
                // 时间上限等待  等待多少纳秒
                t = tailWaits.awaitNanos(t);
            }
            array[tail] = e;
            if (++tail == array.length) {
                tail = 0;
            }
            size++;
            // 唤醒出队
            headWaits.signal();
        } finally {
            lock.unlock();
        }
        return false;
    }

    @Override
    public E poll() throws InterruptedException {
        lock.lockInterruptibly();
        try {
            // 循环等待
            while(isEmpty()) {
                headWaits.await();
            }
            E e = array[head];
            array[head] = null; // help GC
            if (++head == array.length) {
                head = 0;
            }
            size--;
            // 唤醒入队
            tailWaits.signal();
            return e;
        } finally {
            lock.unlock();
        }
    }
}
